package taller.dataLayer.managers;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import taller.dataLayer.entities.Factura;
import taller.dataLayer.vo.FacturaVO;

@Stateless
public class AdministradorFacturasBean implements AdministradorFacturas {
	@PersistenceContext(name="taller14")
	EntityManager entityManager;
	
    public AdministradorFacturasBean() {
    }

    public void guardar(FacturaVO factura) {
    	Factura facturaEB = new Factura();
    	facturaEB.setVO(factura);
    	if (this.buscar(factura) != null) {
			entityManager.merge(facturaEB);
		} else {
			entityManager.persist(facturaEB);
		}
    }
    
	public FacturaVO buscar(FacturaVO factura) {
		Factura retVal = (Factura) entityManager.find(Factura.class, factura.getNumero());
		return retVal != null? retVal.getVO() : null;
	}
	
	@SuppressWarnings("unchecked")
	public List<FacturaVO> buscarTodas() {

		List<Factura> facturas = entityManager.createQuery("from Factura").getResultList();
		List<FacturaVO> facturasVO = new ArrayList<FacturaVO>();
		Iterator<Factura> i = facturas.iterator();
		while(i.hasNext()){
			FacturaVO factura = i.next().getVO();
			facturasVO.add(factura);
		}
		
		return facturasVO;
	}
}
